package upload

import (
	"gq_volunteer_platform/bean"
	"gq_volunteer_platform/model/admin"
	"gq_volunteer_platform/model/material"
	"mime/multipart"
	"os"
	"path"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
)

func IsExist(path string) bool {
	if _, err := os.Stat(path); err != nil {
		if os.IsExist(err) {
			return true
		}
		if os.IsNotExist(err) {
			return false
		}
		return false
	}

	return true
}

func Upload(c *gin.Context) {
	var adm admin.Admin
	if err := adm.Get(c); err != nil {
		bean.Log.Error(err)
		c.String(500, err.Error())
		return
	}

	// single file
	var f *multipart.FileHeader
	if file, err := c.FormFile("file"); err != nil {
		bean.Log.Warning(err)
		c.String(400, err.Error())
		return
	} else {
		f = file
	}

	var dst string

	// uuid
	if u, err := uuid.NewUUID(); err != nil {
		bean.Log.Warning(err)
		c.String(500, err.Error())
		return
	} else {
		dst = u.String() + path.Ext(f.Filename)
	}

	// 拼接年月
	dst = "upload/" + time.Now().Format("2006") + "/" + time.Now().Format("01") + "/" + dst

	if IsExist(dst) {
		bean.Log.Error("发生错误，请重试")
		c.String(500, "发生错误，请重试")
		return
	}

	// Upload the file to specific dst.
	if err := c.SaveUploadedFile(f, dst); err != nil {
		bean.Log.Warning(err)
		c.String(500, err.Error())
		return
	}

	// 记录素材信息
	var mat material.Material
	mat.Name = f.Filename
	mat.Size = f.Size
	mat.Path = dst
	mat.Type = "后台"
	if err := bean.MysqlDb.Create(&mat).Error; err != nil {
		bean.Log.Error(err)
		c.String(500, "数据库错误")
		return
	}

	c.PureJSON(200, gin.H{
		"url": dst,
	})
}
